package groups.geographics.parser;

import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ListIterator;
import java.util.Vector;

import groups.common.DBDumper;
import groups.geographics.Habitat;
import groups.geographics.dao.IHabitatDao;
import groups.geographics.dao.JDBCHabitatDao;

import jxl.Cell;
import jxl.NumberCell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class HabitatParser {
	static private Workbook workbook;

	public static Vector<Habitat> parse() throws BiffException, IOException{
		workbook = Workbook.getWorkbook(new File ("BIOME4-2.xls"));
		Sheet sheet = workbook.getSheet(2);
		Vector<Habitat> habitats = new Vector<Habitat>();
		for(int i=2; i<sheet.getRows(); i++){
			Cell row[] = sheet.getRow(i);
			if(!row[8].getContents().equals("")){
				Habitat habitat = new Habitat();
				habitat.setCoordX((float) ((NumberCell) row[3]).getValue());
				habitat.setCoordY((float) ((NumberCell)row[4]).getValue());
				habitat.setName(row[8].getContents());
				habitats.add(habitat);
			}
		}
		return habitats;
	}
	
	public static void main (String args[]){
		try {
			Vector<Habitat> habitats = parse();
			ListIterator<Habitat> i = habitats.listIterator();
			DBDumper dumper = new DBDumper("org.apache.derby.jdbc.EmbeddedDriver", "jdbc:derby:endemics;create=true", "", "");
			Connection con = dumper.initDB();
			IHabitatDao habitatDao = new JDBCHabitatDao(con);
			while(i.hasNext()){
				habitatDao.create(i.next());
			}
			con.close();
			System.out.println("Todos os dados foram adicionados com sucesso!");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BiffException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}